package com.ssfeng.youxia.shiro;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.util.StringUtils;

import java.io.*;

/**
 * Created by liyuhang on 2019-09-15.
 */
public class SessionUtils {

    public static String SESSION_KICKOUT_KEY = "kickout";

    /***
     *session base64 加密
     * @param session
     * @return
     */
    public static String base64EncodeSession(Session session){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(out);
            objectOutputStream.writeObject(session);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String sessionStr = Base64.encodeToString(out.toByteArray());
        return sessionStr;
    }

    /*****
     *session base64 解密
     * @param sessions
     * @return
     */
    public static Session base64DcodeSession(String sessions) {
        if (StringUtils.isEmpty(sessions)) {
            return null;
        }
        ByteArrayInputStream input = new ByteArrayInputStream(Base64.decode(sessions));
        Session session=null;
        try (ObjectInputStream objectInputStream = new ObjectInputStream(input)) {
            session = (Session) objectInputStream.readObject();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
        return session;
    }


    /***
     *从session中提取用户信息
     * @param session
     * @return
     */
    public static ShiroUser getUserFromSession(Session session) {
        Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (obj == null) {
            return null;
        }
        if (obj instanceof SimplePrincipalCollection){
            SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) obj;
            ShiroUser user = (ShiroUser) simplePrincipalCollection.getPrimaryPrincipal();
            return user;
        }
        return null;
    }
}
